package cn.wolfcode.luowowo.order.service.impl;

import cn.wolfcode.luowowo.article.domain.TicketDetail;
import cn.wolfcode.luowowo.cache.service.IUserRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.order.domain.TicketOrder;
import cn.wolfcode.luowowo.order.reponsitory.TicketOrderReponsitory;
import cn.wolfcode.luowowo.order.service.ITicketOrderService;
import cn.wolfcoe.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class TicketOrderServiceImpl implements ITicketOrderService {

    @Autowired
    private TicketOrderReponsitory reponsitory;
    @Reference
    private IUserRedisService userRedisService;

    @Override
    public void save(TicketOrder ticketOrder, String msgCode, UserInfo userInfo) throws LogicException{
        //数据校验
        checkStr( ticketOrder.getUsername(), "取票人不能为空" );
//        checkStr( ticketOrder.getPeopleType(), "去选择票种" );
//        checkStr( msgCode, "验证码不能为空" );
//        checkStr( ticketOrder.getPhone(), "手机号不能为空" );
//        checkStr( ticketOrder.getInNo(), "身份证不能为空" );
//        checkStr( ticketOrder.getPno() + "", "商品编码不能为空" );
//        checkStr( ticketOrder.getOrdrNum() + "", "请输入数量" );
//        //验证手机号格式
//        if (ticketOrder.getPhone().length() != 11) {
//
//            throw new LogicException( "手机号格式不正确" );
//        }
//        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9])|(16[6]))\\d{8}$";
//        Pattern p = Pattern.compile( regex );
//        Matcher m = p.matcher( ticketOrder.getPhone() );
//        boolean isMatch = m.matches();
//        if (!isMatch) {
//            throw new LogicException( "手机号格式不正确" );
//        }
//        //验证手机验证码
//        String key = RedisKeys.VERIFY_CODE.join( ticketOrder.getPhone() );
//        String redisCode = userRedisService.getUserInfoRedis( key );
//        //注意返回是boolean类型的数据,是可以直接取反的
//        if (redisCode == null || !redisCode.equals( msgCode )) {
//            throw new LogicException( "验证码错误或者已过期" );
//        }
        //设置值
        ticketOrder.setUserInfo( userInfo );
        ticketOrder.setCreateTime( new Date() );
        reponsitory.save( ticketOrder );
    }

    @Override
    public void updateOrderState(String out_trade_no) {

        TicketOrder ticketOrder = reponsitory.findByOrderNO( out_trade_no );
        ticketOrder.setState( TicketOrder.ORDER_STATE_SUCCESS );
        reponsitory.save( ticketOrder );

    }

    private void checkStr(String str, String msg) {
        if (str == null || str.length() == 0) {
            throw new LogicException( msg );
        }
    }
}
